package com.cykj.user.service.impl;

import com.cykj.common.core.domain.R;
import com.cykj.system.api.RemoteShopService;
import com.cykj.user.domain.Store;
import com.cykj.user.mapper.ShopCategoryMapper;
import com.cykj.user.mapper.StoreMapper;
import com.cykj.user.service.ICollectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CollectServiceimpl implements ICollectService {

    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private ShopCategoryMapper shopCategoryMapper;
    @Resource
    private RemoteShopService remoteShopService;

    @Override
    public List<Store> getCollectShops(Long customerId) {
        // 直接查询数据库
        List<Store> collectList = storeMapper.selectByCustomerId(customerId);

        // 关联查询商家信息
        collectList.forEach(store -> {
            try {
                // 通过Feign调用商家微服务获取店铺信息
                R<Map<String, Object>> shopResult = remoteShopService.getShopInfo(store.getBusinessId());
                if (shopResult != null && shopResult.getCode() == 200) {
                    Map<String, Object> shopInfo = shopResult.getData();
                    store.setShopName((String) shopInfo.get("shopName"));
                    store.setShopAvatar((String) shopInfo.get("shopAvatar"));
                    // 设置坐标信息
                    if (shopInfo.get("longitude") != null) {
                        store.setLongitude(Double.parseDouble(shopInfo.get("longitude").toString()));
                    }
                    if (shopInfo.get("latitude") != null) {
                        store.setLatitude(Double.parseDouble(shopInfo.get("latitude").toString()));
                    }
                    // 新增：设置类目名称
                    if (shopInfo.get("shopCategory") != null) {
                        Integer categoryId = (Integer) shopInfo.get("shopCategory");
                        String categoryName = shopCategoryMapper.selectCategoryNameById(categoryId);
                        store.setShopCategoryName(categoryName);
                    }
                    // 设置营业时间
                    if (shopInfo.get("shopStart") != null) {
                        store.setShop_start(LocalTime.parse(shopInfo.get("shopStart").toString()));
                    }
                    if (shopInfo.get("shopEnd") != null) {
                        store.setShop_end(LocalTime.parse(shopInfo.get("shopEnd").toString()));
                    }

                    // 设置店铺评分
                    if (shopInfo.get("shopGrade") != null) {
                        store.setShopGrade(Double.parseDouble(shopInfo.get("shopGrade").toString()));
                    }

                }
            } catch (Exception e) {
                log.error("获取商家信息失败: {}", e.getMessage());
            }
        });

        log.info("直接查询收藏列表，customerId={}，数据量={}", customerId, collectList.size());
        return collectList;
    }

    @Override
    @Transactional
    public int addCollectShop(Long businessId, Long customerId) {
        // 1. 检查是否已收藏
        Store exist = storeMapper.selectByBusinessAndCustomer(businessId, customerId);
        if (exist != null) {
            if (exist.getCollectStatus() == 1) {
                return 0; // 已收藏
            }
            // 2. 更新收藏状态
            exist.setCollectStatus(1);
            exist.setCreateTime(new Date());
            return storeMapper.updateStore(exist);
        } else {
            // 3. 新增收藏
            Store store = new Store();
            store.setBusinessId(businessId);
            store.setCustomerId(customerId);
            store.setCreateTime(new Date());
            store.setCollectStatus(1);
            return storeMapper.insertStore(store);
        }
    }

    @Override
    @Transactional
    public int cancelCollectShop(Long collectId) {
        Store store = storeMapper.selectById(collectId);
        if (store == null) {
            return 0;
        }
        return cancelCollectByBusinessAndCustomer(store.getBusinessId(), store.getCustomerId());
    }

    @Override
    @Transactional
    public int cancelCollectByBusinessAndCustomer(Long businessId, Long customerId) {
        // 直接更新数据库
        Store store = storeMapper.selectByBusinessAndCustomer(businessId, customerId);
        if (store == null || store.getCollectStatus() == 0) {
            return 0;
        }

        store.setCollectStatus(0);
        int result = storeMapper.updateStore(store);

        log.info("取消收藏操作 - businessId: {}, customerId: {}, 结果: {}",
                businessId, customerId, result);

        return result;
    }

    @Override
    public boolean checkCollectStatus(Long shopId, Long userId) {
        // 直接查询数据库
        Store store = storeMapper.selectByBusinessAndCustomer(shopId, userId);
        return store != null && store.getCollectStatus() == 1;
    }
}
